const axios = require('axios');
const iconv = require('iconv-lite');
const cheerio = require('cheerio');

const getGoldData = async () => {
    const response = await axios.get('https://www.guijinshu.com/plugin.php?id=study_dz_goldapi', { responseType: 'arraybuffer' });
    let decodedStr = iconv.decode(new Buffer.from(response.data), 'utf8');
    const $ = cheerio.load(decodedStr);
    const tableElement = $('#wp>.m-gold').find('table>tbody').eq(0).find('tr');
    let SJSData = [];
    tableElement.each((i, item) => {
        const name = $(item).find('td>.product-name').text();
        const recentPrice = $(item).find('td').eq(1).text();
        const topPrice = $(item).find('td').eq(2).text();
        const bottomPrice = $(item).find('td').eq(3).text();
        const openPrice = $(item).find('td').eq(4).text();
        const updateTime = $(item).find('td').eq(5).text();
        // console.log(name);
        SJSData.push({
            name,
            recentPrice,
            topPrice,
            bottomPrice,
            openPrice,
            updateTime,
        })
    })
    const tableElement2 = $('#wp>.m-gold').find('table>tbody').eq(1).find('tr');
    let SBData = [];
    tableElement2.each((i, item) => {
        const name = $(item).find('td>.product-name').text();
        const taxExclusivePrice = $(item).find('td').eq(1).text(); //不含税，无票
        const wage = $(item).find('td').eq(2).text(); //工费
        const taxInclusivePrice = $(item).find('td').eq(3).text();
        // const openPrice = $(item).find('td').eq(4).text();
        const updateTime = $(item).find('td').eq(5).text();
        // console.log(name);
        SBData.push({
            name,
            taxExclusivePrice,
            wage,
            taxInclusivePrice,
            // openPrice,
            updateTime,
        })
    })
    const tableElement3 = $('#wp>.m-gold').find('table>tbody').eq(2).find('tr');
    const otherBrands = [];
    tableElement3.each((i, item) => {
        const name = $(item).find('td>.product-name').text();
        const recentPrice = $(item).find('td').eq(1).text();
        const topPrice = $(item).find('td').eq(2).text();
        const bottomPrice = $(item).find('td').eq(3).text();
        const openPrice = $(item).find('td').eq(4).text();
        const updateTime = $(item).find('td').eq(5).text();
        // console.log(name);
        otherBrands.push({
            name,
            recentPrice,
            topPrice,
            bottomPrice,
            openPrice,
            updateTime,
        })
    })
    return {
        SJSData,
        SBData,
        otherBrands,
    }
}

module.exports = {
    getGoldData,
}